package nix.dbutils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import nix.jdbc.JdbcUtils;

public class TestQR {

	@Test
	public void add() throws SQLException {
		Connection con = JdbcUtils.getConnection();
		QR<Student> qr = new QR<Student>(con);
		qr.update("insert into stu (id, name) values (?, ?)", 2, "liSi");
	}

	@Test
	public void load() throws SQLException {
		Connection con = JdbcUtils.getConnection();
		QR<Student> qr = new QR<Student>(con);
		// 内部实现类
		RSHandler<Student> orh = new RSHandler<Student>() {
			@Override
			public Student handler(ResultSet rs) throws SQLException {
				if (!rs.next())
					return null;
				Student stu = new Student();
				stu.setId(rs.getInt("id"));
				stu.setName(rs.getString("name"));
				return stu;
			}
		};
		Student stu = qr.query("select * from stu where id = ?", orh, 2);
		System.out.println(stu);
	}

	@Test
	public void queryAll() throws SQLException {
		Connection con = JdbcUtils.getConnection();
		QR<List<Student>> qr = new QR<List<Student>>(con);
		// 内部实现类
		RSHandler<List<Student>> orh = new RSHandler<List<Student>>() {
			@Override
			public List<Student> handler(ResultSet rs) throws SQLException {
				List<Student> list = new ArrayList<Student>();
				while (rs.next()) {
					Student stu = new Student();
					stu.setId(rs.getInt("id"));
					stu.setName(rs.getString("name"));
					list.add(stu);
				}
				return list;
			}
		};
		List<Student> list = qr.query("select * from stu", orh);
		for (Student student : list) {
			System.out.println(student);
		}
	}
}
